/*
 * Copyright (C) 2009 Leandro Aparecido <lehphyro@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.metalframework.jsf.scope;

import java.util.*;

import javax.faces.context.*;

import org.slf4j.*;

public abstract class AbstractFacesScope extends FacesScope {

	protected static final String PREFIX_SEPARATOR = ".";
	
	private static final Logger logger = LoggerFactory.getLogger(AbstractFacesScope.class);
	
	@Override
	public void onStartRequest() {
		// Do nothing
	}
	
	@Override
	public void onEndRequest() {
		// Do nothing
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public <T> T get(String name) {
		Object value = internalGet(name);
		logger.debug("Retrieving attribute [{}] from [{}] scope with value [{}]", new Object[] { name, getType(), value });
		
		return (T)value;
	}
	
	@SuppressWarnings("unchecked")
	protected <T> T internalGet(String name) {
		return (T)getStore().get(buildName(name));
	}
	
	@Override
	public void set(String name, Object obj) {
		logger.debug("Setting attribute [{}] with value [{}] in the [{}] scope", new Object[] { name, obj, getType() });
		internalSet(name, obj);
	}
	
	protected void internalSet(String name, Object obj) {
		getStore().put(buildName(name), obj);
	}
	
	@Override
	public void remove(String name) {
		logger.debug("Removing attribute [{}] from the [{}] scope", name, getType());
		internalRemove(name);
	}
	
	protected void internalRemove(String name) {
		getStore().remove(buildName(name));
	}
	
	@Override
	public boolean contains(String name) {
		return getStore().containsKey(buildName(name));
	}

	protected void clear() {
		logger.debug("Clearing [{}] scope completely", getType());

		for (String attributeName : getStore().keySet()) {
			if (attributeName.startsWith(getPrefix())) {
				internalRemove(getRawName(attributeName));
			}
		}
	}
	
	protected Map<String, Object> getStore() {
		return FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
	}
	
	protected String buildName(String name) {
		return getPrefix() + name;
	}
	
	protected String getRawName(String name) {
		return name.replace(getPrefix(), "");
	}
	
	protected String getPrefix() {
		return getType().getName() + PREFIX_SEPARATOR;
	}
	
	protected abstract FacesScopeType getType();
	
}
